<html>

<head>
  <script src="./konva.min.js"></script>
  <meta charset="utf-8" />
  <title> emo</title>
  <style>
    body {
      margin: 0;
      padding: 0;
      overflow: hidden;
      background-color: #f0f0f0;
    }
  </style>
</head>

<body>
  <div>

    长：<input type="text" id="box1" value="200">
    宽：<input type="text" id="box2" value="200"> <button onclick="setGesture()">画一个矩形</button>
    <div>
      <button  onclick="createLine()">连接</button>
    </div>
  </div>
  <div id="container"></div>
  <script>

    var _width = window.innerWidth;
    var _height = window.innerHeight;

    var stage = new Konva.Stage({
      container: 'container',
      width: _width,
      height: _height,
    });

    var layer = new Konva.Layer();
    stage.add(layer);

    var tr = new Konva.Transformer({ 
        anchorStroke: 'red',
        anchorFill: 'yellow',
        anchorSize: 20,
        borderStroke: 'green',
        borderDash: [3, 3]
      })
    layer.add(tr)
    let count = 0;
    function setGesture() {
      const width = +document.getElementById('box1').value
      const height = +document.getElementById('box2').value
      var rect = new Konva.Rect({
        id:'box'+count,
        x: 20,
        y: 20,
        width,
        height,
        fill: '#cfcfcf',
        stroke: 'black',
        strokeWidth: 1,
        draggable: true,
      });
      rect.on('dragmove', ()=>{
        connectLine()
      })

      layer.add(rect);
      count++;
    }

    

    // 点击事件
    stage.on('click tap', function(e) {    
      
        if (e.target === stage) {
          tr.nodes([]);  
          return;
        }
      const metaPressed = e.evt.shiftKey || e.evt.ctrlKey || e.evt.metaKey;
      const isSelected = tr.nodes().indexOf(e.target) >= 0;
        if (!metaPressed && !isSelected) {
          tr.nodes([e.target]);
        } 
    })
    

    function connectLine() {
      
      const line = layer.findOne('#line');
      const rect0 = layer.findOne('#box0');
      console.log(rect0.width() )
      const rect1 = layer.findOne('#box1');
      line.points([rect0.x()+100, rect0.y()+100, rect1.x()+100, rect1.y()+100])
    }

    function createLine() {
      var line = new Konva.Arrow({
        id: 'line',
        x: 10,
        y: 10,
        points: [0, 0, 20, 300],
        pointerLength: 10,
        pointerWidth: 10,
        fill: 'black',
        stroke: 'black',
        strokeWidth: 2,
      });
      layer.add(line);
      connectLine()
    }
  

  </script>
</body>

</html>